package edu.ptu.acl.controller;


import edu.ptu.acl.common.MyConstants;
import edu.ptu.acl.common.ResultVO;
import edu.ptu.acl.dto.RoleModuleTreeDto;
import edu.ptu.acl.dto.param.RoleModuleParam;
import edu.ptu.acl.entity.RoleModule;
import edu.ptu.acl.service.IRoleModuleService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Min;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author LinJC
 * @since 2022-03-15
 */
@RestController
@RequestMapping("/roleModule")
@Validated
public class RoleModuleController {

    @Resource
    private IRoleModuleService roleModuleService;

    //获取所有角色模块
    @GetMapping("/getAllRoleModule")
    public ResultVO getAllRoleModule() {
        List<RoleModuleTreeDto> tree = roleModuleService.getTree();
        return ResultVO.success(tree);
    }

    //新增角色模块信息
    @PostMapping("/saveRoleModule")
    public ResultVO saveRoleModule(@RequestBody @Validated(RoleModuleParam.Save.class) RoleModuleParam roleModuleParam) {
        roleModuleService.validateName(roleModuleParam.getParentId(),roleModuleParam.getName());
        RoleModule roleModule = RoleModule.builder().name(roleModuleParam.getName()).parentId(roleModuleParam.getParentId())
                .seq(roleModuleParam.getSeq()).build();
        roleModuleService.save(roleModule);
        return ResultVO.success();
    }

    //编辑角色模块信息
    @PutMapping("/updateRoleModule")
    public ResultVO updateRoleModule(@RequestBody @Validated(RoleModuleParam.Update.class) RoleModuleParam roleModuleParam) {
        roleModuleService.validateName(roleModuleParam.getParentId(),roleModuleParam.getName());
        RoleModule roleModule = RoleModule.builder().name(roleModuleParam.getName()).parentId(roleModuleParam.getParentId())
                .seq(roleModuleParam.getSeq()).id(roleModuleParam.getId())
                .version(roleModuleParam.getVersion()).build();
        if (roleModuleService.updateById(roleModule)) {
            return ResultVO.success();
        }
        return ResultVO.fail(MyConstants.ResultCode.OPTIMISTIC_LOCKING);
    }

    //删除角色模块信息
    @DeleteMapping("/deleteRoleModule/{id}")
    public ResultVO deleteRoleModule(@PathVariable @Min(value = 10000000000000000L, message = "id不规范") Long id) {
        roleModuleService.validateRole(id);
        roleModuleService.removeById(id);
        return ResultVO.success();
    }

}
